package rursu.providers;

import java.util.List;

import rursu.business.R;
import rursu.business.pojo.Certification;
import rursu.business.pojo.Movie;
import rursu.business.pojo.MovieImage;
import rursu.providers.callback.ImageLoaderCallback;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

public class MovieArrayAdapter extends ArrayAdapter<Movie> implements ImageLoaderCallback {

	private Activity context;
	private final String LOGGER_TAG = MovieArrayAdapter.class.getCanonicalName();
	private List<Movie> movies;

	public MovieArrayAdapter(Activity context, int textViewResourceId,
			List<Movie> movies) {
		super(context, textViewResourceId, movies);
		this.movies = movies;
		this.context = context;
	}
	
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		View view = null;
		if ( (view = convertView) == null ) {
			view = context.getLayoutInflater().inflate(R.layout.item_layout, parent, false);
		}
		
		Movie movie = getItem(position);

		ImageView icon = (ImageView) view.findViewById(R.id.film_icon);
//		icon.setImageResource(R.drawable.default_film_image);
		
		if ( movie.getPoster() != null ) {
			icon.setImageBitmap(movie.getPoster());			
		} else {
			icon.setImageResource(R.drawable.default_film_image);			
		}

		TextView filmName = (TextView) view.findViewById(R.id.film_name);
		filmName.setText(movie.getName());

		RatingBar ratingBar = (RatingBar) view.findViewById(R.id.fan_rating);
		ratingBar.setRating(movie.getRating());
		
		TextView runTime = (TextView) view.findViewById(R.id.run_time);
		runTime.setText("");

		TextView releaseDate = (TextView) view.findViewById(R.id.release_date);
		releaseDate.setText(movie.getReleased());
		
		ImageView certificationImage = (ImageView) view.findViewById(R.id.certification);
		
		Certification crtf = Certification.getCertificationt(movie.getCertification());
		if ( crtf != null ) {
			certificationImage.setImageResource(crtf.getResource());
		}

		return view;
	}


	public void onImageLoaded(MovieImage image) {
		
		for (Movie movie : movies) {
			if (movie.getId() == image.getMovieId()) {
				movie.setPoster(image.getBitmap());
			}
		}
		
		notifyDataSetChanged();
	}


	public void onImageLoadCancelled(String reason) {
		// TODO Auto-generated method stub
		
	}


	public void onImagePreLoad(MovieImage image) {
		// TODO Auto-generated method stub
		
	}


	public void onLoadFinished(int imageNumber) {
		// TODO Auto-generated method stub
		
	}
	
	
}
